/**
 * 
 */
package org.ChrisRiffle.Acme.AcmeTraverser.ActionPerformers;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import org.ChrisRiffle.Acme.AcmeTraverser.AbstractActionPerformer;

/**
 * Calculates average file size
 * 
 * @author RIF
 *
 */
public class AvgFileSizeActionPerformer extends AbstractActionPerformer {

	private final String OUTPUT_FILE_NAME = "AvgFileSizeActionPerformer_output.txt";
	
	private long byteSumOfAllFiles = 0;
	
	private long fileProcessedCount = 0;
	
	/**
	 * Performs the action on the specified file
	 * @param pFile
	 * 			 The file or directory to act upon
	 * 
	 * @see org.ChrisRiffle.Acme.AcmeTraverser.ActionPerformer#doAction(java.io.File)
	 */
	@Override
	public void doAction(File pFile) {

		if (pFile == null || pFile.isDirectory() || !pFile.isFile()) {

			//ignore, we're only interested in actual Files on disk
			return;
			
		}else{
			
			//process the file
			byteSumOfAllFiles += pFile.length();		
			
			fileProcessedCount++;			
		}
		
	}


	/**
	 * Saves the processed result to a file in the system user directory 
	 * based on the jvm property
	 */
	@Override
	public void shutDown() {

		try {
			
			writeResultsToOutputFile();
			
			getBufferedWriter().close();
			
			Logger.getAnonymousLogger().info("Wrote results to: "
					+ getOutputFile().getCanonicalPath());
			
		} catch (IOException e) {

			e.printStackTrace();
			
			Logger.getAnonymousLogger().severe(
					"FAILED writing results to: " + OUTPUT_FILE_NAME);
		}

	}
	
	
	/**
	 * writeResultsToOutputFile
	 * @throws IOException
	 * 				If unable to writeResultsToOutputFile 
	 */
	private void writeResultsToOutputFile() throws IOException{
		
		long avgFileSize = byteSumOfAllFiles / fileProcessedCount;				
		
		String avgStr = "Avg File Size: " + avgFileSize + " bytes";
		String countStr = "File # Count: " + fileProcessedCount + " files"; 
		
		getBufferedWriter().write(avgStr);		
		getBufferedWriter().newLine();		
		getBufferedWriter().write(countStr);
		
		Logger.getAnonymousLogger().info(avgStr);		
		Logger.getAnonymousLogger().info(countStr);
		
	}


	@Override
	public String getOutputFileName() {

		return OUTPUT_FILE_NAME;
	}
	


}
